package com.ysd.user.controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ysd.common.entity.User;
import com.ysd.common.utils.Json;
import com.ysd.user.service.UserService;
import com.ysd.user.utils.PageUtil;
import com.ysd.user.utils.ResponeMessageUtil;


@Controller
@RequestMapping("/back/")
@ResponseBody
public class BackUserController {
	
	@Autowired
	private UserService userService;
	
	
	/**
	 * 去登录页面
	 * @return
	 */
	@RequestMapping("/toLogin")
	public String toLogin() {
		return "backPage/login";
	}
	
	/**
	 * 退出账户的操作
	 * @param session
	 * @return
	 */
	@RequestMapping("/loginOut")
	public String loginOut(HttpSession session) {
		session.removeAttribute("userInfo");
		return "backPage/login";
	}
	
	/**
	 * 后台登录时的验证
	 * @param name
	 * @param password
	 * @param model
	 * @param session
	 * @return
	 */
	@RequestMapping("/login")
	public Json login(@RequestParam("name")String name,@RequestParam("password")String password,Model model,HttpSession session) {
		Json json = new Json();
		if(name != null && name != "" && password != null && password != "") {
			User user = userService.backLogin(name, password);
			if(user != null) {//登录成功后进来
				session.setAttribute("userInfo", user);
				userService.editUserLastLoginTimeById(user.getUserId());
				userService.eidtUserErrorCountById(user.getUserId(),0,null);
				Json.success(user);
			}
			//查询一下是否存在该用户如存在就记录错误次数
			User userVerify = userService.queryUserByNameVerifyError(name);
			//获得当前系统时间
			Date date = new Date();
			DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String datestr = dateFormat.format(date);//当前系统时间
			Calendar calendar = Calendar.getInstance();
			if(userVerify != null && userVerify.getErrorCount() < 4) {//密码错误执行
				//连续用户名相同时执行
				if(session.getAttribute("userId") != null && session.getAttribute("userId") != "" && (Integer) session.getAttribute("userId") == userVerify.getUserId()) {
					//得到存储错误次数
					int errorCount = userVerify.getErrorCount() + 1;
					//记录到的错误次数存入到数据库中
					userService.eidtUserErrorCountById((Integer) session.getAttribute("userId"),errorCount,datestr);
					//model.addAttribute("msg","账户或密码错误,还有" + (5-userVerify.getErrorCount()-1) +"次登陆机会");
					json.fail("账户或密码错误,还有" + (5-userVerify.getErrorCount()-1) +"次登陆机会");
				}else if(session.getAttribute("userId") != null && session.getAttribute("userId") != "" && (Integer) session.getAttribute("userId") != userVerify.getUserId()) {//用户名不同时执行
					//得到存储错误次数
					int errorCount = userVerify.getErrorCount() + 1;
					//记录到的错误次数存入到数据库中
					userService.eidtUserErrorCountById(userVerify.getUserId(),errorCount,datestr);
					//格式化之前用户的错误次数为0
					userService.eidtUserErrorCountById((Integer) session.getAttribute("userId"),0,null);
					//两次用户名不一样删除session域
					session.removeAttribute("userId");
					//model.addAttribute("msg","账户或密码错误,还有" + (5-userVerify.getErrorCount()-1) +"次登陆机会");
					json.fail("账户或密码错误,还有" + (5-userVerify.getErrorCount()-1) +"次登陆机会");
				}
				//得到存储错误次数
				int errorCount = userVerify.getErrorCount() + 1;
				userService.eidtUserErrorCountById(userVerify.getUserId(),errorCount,datestr);
				//model.addAttribute("msg","账户或密码错误,还有" + (5-userVerify.getErrorCount()-1) +"次登陆机会");
				
				session.setAttribute("userId", userVerify.getUserId());
			}else if(userVerify != null && userVerify.getErrorCount() == 4) {
				userService.eidtUserErrorCountById(userVerify.getUserId(),5,datestr);
				userService.editUserIsLockById(userVerify.getUserId(), 1);
				//model.addAttribute("msg","您的账户已被锁定，请1分钟之后再次尝试登陆");
				json.fail("您的账户已被锁定，请1分钟之后再次尝试登陆");
			}else if(userVerify != null && userVerify.getIsLock() == 1) {//已被锁定执行
				//获得错误时间
				String lastLoginErrorTime = userVerify.getLastLoginErrorTime();
				try {
					calendar.setTime(dateFormat.parse(lastLoginErrorTime));
					calendar.add(Calendar.SECOND, +60);//定义隔多长时间
					String format = dateFormat.format(calendar.getTime());//增加1分钟后的时间
					Date loginErrorTime = dateFormat.parse(format);//锁定时间
					Date dateTime = dateFormat.parse(datestr);//当前时间
					//判断错误时间是否小于当前时间，如果大于就说明解锁时间还没到
					if( loginErrorTime.getTime() < dateTime.getTime()) {
						userService.editUserIsLockById(userVerify.getUserId(),0);
						json.rs("msg","已解锁，请重新尝试！",true);
					}else {
						long between = loginErrorTime.getTime() - dateTime.getTime();
						long day = between / (24 * 60 * 60 * 1000);
						long hour = (between / (60 * 60 * 1000) - day * 24);
						long min = ((between / (60 * 1000)) - day * 24 * 60 - hour * 60);
						long s = (between / 1000 - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60);
						//model.addAttribute("msg","您的账户已被锁定，请在"+day + "天" + hour + "小时" + min + "分" + s + "秒"+"之后再次尝试登陆");
						json.fail("您的账户已被锁定，请在"+day + "天" + hour + "小时" + min + "分" + s + "秒"+"之后再次尝试登陆");
						
					}
				} catch (ParseException e) {
				     e.printStackTrace();
				}
			}else {
				json.fail("该用户没有注册信息");
			}
		}else {
			//model.addAttribute("msg","内容不能为空");
			json.fail("内容不能为空");
			
		}
		return json;
	}
	
	
	/**
	 * 查询出所有的用户
	 * @return
	 */
	@RequestMapping("/queryAllUser")
	public ResponeMessageUtil queryAllUser(int page,int limit,String name,String gender,String isAdmin) {
		Integer setValue = PageUtil.getSetValue(page, limit);
		return ResponeMessageUtil.ok(userService.queryUserCounts(name, gender,isAdmin), userService.queryAllUser(setValue,limit,name,gender,isAdmin));
	}
	
	/**
	 * 添加一个用户
	 * @param isAdminStatus
	 * @param user
	 * @return
	 */
	@RequestMapping("/addUser")
	public Boolean addUser(String isAdminStatus, User user) {
		if(isAdminStatus != null && isAdminStatus != "" && isAdminStatus.equals("on")) {
				user.setIsAdmin(1);
		}else {
			user.setIsAdmin(0);
		}
		return userService.addUser(user);
	}
	
	
	/**
	 * 编辑用户的基础信息
	 * @param isAdminStatus
	 * @param user
	 * @return
	 */
	@RequestMapping("/editUserById")
	public Boolean editUserById(String isAdminStatus, User user) {
		//获得传入的是否为管理员状态如是者传的值为on，再就行赋值为对应的1（是）0（不是）
		if(isAdminStatus != null && isAdminStatus != "" && isAdminStatus.equals("on")) {
			user.setIsAdmin(1);
		}else {
			user.setIsAdmin(0);
		}
		//获得业务层返回的执行结果，修改成功者返回为true
		System.out.println(user);
		return userService.editUserById(user);
	}
	
	/**
	 * 进行批量的删除操作
	 * @param ids
	 * @return
	 */
	@RequestMapping("/delAllUserByIds")
	public Boolean delAllUserByIds(@RequestParam("ids")String ids) {
		return userService.delAllUserByIds(ids);
	}
	
	/**
	 * 删除单个的用户
	 * @param id
	 * @return
	 */
	@RequestMapping("/delUserById/{id}")
	public Boolean delUserById(@PathVariable("id") int id) {
		return userService.delUserById(id);
	}
	
	/**
	 * 编辑用户的是否锁定账号的状态
	 * @param id
	 * @param valid
	 * @return
	 */
	@RequestMapping("/editUserIsLockById/{id}/{valid}")
	public Boolean editUserIsLockById(@PathVariable("id") Integer id,@PathVariable("valid") String valid) {
		Integer number = 0;
		if(valid != null && valid != "" && valid.equals("on")) {
			number = 1;
		}else {
			number = 0;
		}
		return userService.editUserIsLockById(id,number);
	}
	
	@RequestMapping("/editUserAdminStatusById/{id}/{valid}")
	public Boolean editUserAdminStatusById(@PathVariable("id") Integer id,@PathVariable("valid") String valid) {
		Integer number = 0;
		if(valid != null && valid != "" && valid.equals("on")) {
			number = 1;
		}else {
			number = 0;
		}
		return userService.editUserAdminStatusById(id,number);
	}
	
	
	/**
	 * 在个人信息页编辑基础的登录者用户信息
	 * @param user
	 * @return
	 */
	@RequestMapping("/editUserBasicInformationById")
	public Boolean editUserBasicInformationById(User user) {
		return userService.editUserBasicInformationById(user);
	}
	
	/**
	 * 查询出所有用户的信息根据name来查询如查询出有者给提示信息用户名不能重复
	 * @param newName
	 * @return
	 */
	@RequestMapping("/queryAllUserByNameWitchVerify/{newName}")
	public Boolean queryAllUserByNameWitchVerify(@PathVariable("newName") String newName) {
		return userService.queryAllUserByNameWitchVerify(newName);
	}
	
}
